#include <leveldb/db.h>
#include <iostream>
#include <ctime>


int main() {

    // Create a levelDB.
    leveldb::Options options;
    options.create_if_missing = true;
    std::string dbPath = "./data";
    leveldb::DB  *db;
    auto status = leveldb::DB::Open(options, dbPath.c_str(), &db);

    if (!status.ok()) {
        std::cerr << "Create Level DB Fail!" << std::endl;
        return 0;
    }


    auto writeBeginTime = std::time(nullptr);
    std::localtime(&writeBeginTime);
    std::cout << writeBeginTime << std::endl;

    // Write key: val
    leveldb::WriteOptions writeOptions;
    writeOptions.sync = false;
    for (int i = 0; i <= 1000000; ++i) {
        std::string key = "name" + std::to_string(i);
        std::string val = "value" + std::to_string(i);
        status = db->Put(writeOptions, key.c_str(), val.c_str());
        if (!status.ok()) {
            std::cerr << "Put Error!";
            return 0;
        }
    }

    auto writeEndTime = std::time(nullptr);
    std::localtime(&writeEndTime);
    std::cout << writeEndTime << std::endl;

    std::cout << "Write Consume Time: " << writeEndTime - writeBeginTime << std::endl;

    // Read val for key.
    leveldb::ReadOptions readOptions;
    for (int i = 0; i <= 10000; ++i) {
        std::string key = "name" + std::to_string(i);
        std::string val;
        status = db->Get(readOptions, key.c_str(), &val);
        if (!status.ok() || val != "value" + std::to_string(i)) {
            std::cerr << "Get Error!";
            return 0;
        }
    }

    auto readEndTime = std::time(nullptr);
    std::localtime(&readEndTime);
    std::cout << readEndTime << std::endl;
    std::cout << "Read Consume Time: " << readEndTime - writeEndTime << std::endl;

    // Close DB.
    delete db;
    return 0;
}
